package com.jason.quectel0805.net;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author：Jason
 * @date：2022/8/8 13:20
 * @email：1129847330@qq.com
 * @description: eg：https://wanandroid.com/article/list/0/json?author=鸿洋
 */
public class HttpUtils {
    private static final String TAG = "jasonwan";

    public static String getNetData(String address) {
        try {
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = connection.getInputStream();
                String content = getStrFromIS(inputStream);
                Log.d(TAG, "getNetData: " + content);
                return content;
            } else {
                InputStream errorStream = connection.getErrorStream();
                String errorMsg = getStrFromIS(errorStream);
                Log.d(TAG, "error: " + errorMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("jasonwan", "getNetData: " + e.getMessage());
        }
        return "";
    }

    public static String getStrFromIS(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        for (int l; (l = inputStream.read(buffer)) != -1; ) {
            result.write(buffer, 0, l);
        }

        return result.toString("UTF-8");
    }

    public static String getStringFromInputStream(InputStream inputStream) {
        try {
            int result = 0;
            StringBuilder sb = new StringBuilder();
            while ((result = inputStream.read()) != -1) {
                sb.append(((char) result));
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("jasonwan", "getStringFromInputStream: " + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}